//
//  QSLouKongLabel.swift
//  TestSwift
//
//  Created by Song on 2019/11/2.
//  Copyright © 2019 Song. All rights reserved.
//

import UIKit

class QSLouKongLabel: UILabel {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        super.backgroundColor = .clear
        self.isOpaque = false
        self.textColor = .white
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        
        super.draw(rect)
        
        guard let context = UIGraphicsGetCurrentContext() else { return }
        let image = context.makeImage()
        UIGraphicsEndImageContext()
        
        guard let context1 = UIGraphicsGetCurrentContext() else { return }
        
        context1.concatenate(CGAffineTransform.init(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: rect.height))
        
        if let img = image {
            if let mask = CGImage.init(maskWidth: img.width, height: img.height, bitsPerComponent: img.bitsPerComponent, bitsPerPixel: img.bitsPerPixel, bytesPerRow: img.bytesPerRow, provider: img.dataProvider!, decode: img.decode, shouldInterpolate: img.shouldInterpolate) {
                context1.clear(rect)
                context1.saveGState()
                context1.clip(to: rect, mask: mask)
                
                if self.layer.cornerRadius != 0.0 {
                    let path = CGPath.init(roundedRect: rect, cornerWidth: self.layer.cornerRadius, cornerHeight: self.layer.cornerRadius, transform: nil)
                    context1.addPath(path)
                    context1.clip()
                }
                
                self.qs_drawBackground(in: rect)
                context1.restoreGState()
            }
        }
    }
    
    // MARK: - Func
    private func qs_drawBackground(in reat: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        maskedBackgroundColor.set()
        context?.fill(reat)
    }
    
    // MARK: - Property
    private var maskedBackgroundColor: UIColor = .white
    
    private var _backgroundColor: UIColor?
    override var backgroundColor: UIColor? {
        get {
            return _backgroundColor
        }

        set {
            _backgroundColor = newValue
            maskedBackgroundColor = newValue ?? .white
            self.setNeedsDisplay()
        }
    }
}
